define(['util', 'ajax'], function (util, ajax) {
    "use strict";

    var exports = {},
		ViewModel;

    ViewModel = function (data) {
        var self = this;
        self.name = ko.observable();
        self.tags = ko.observable();
        self.referenceId = ko.observable();
        self.referenceName = ko.observable();
        self.description = ko.observable();
        self.imageData = ko.observable();

        self.tempImage = ko.observable();

        self.tempImage.subscribe(function (newValue) {
            var canvas = document.getElementById("imgCanvas");
            util.image.drawImage(canvas, newValue);
            self.imageData(canvas.toDataURL());
        });

        self.tempImage(util.image.checkOrDefault(self.imageData()));

        self.selectPhoto = function () {
            $("#inputFile").click();
        };

        self.capturePhoto = function () {
            $("#inputFile").click();
        };

        $.subscribe('filesDropped', function (files) {

            if (files.length == 0) return;
            var fileToLoad = files[0];
            var fileReader = new FileReader();
            fileReader.onload = function (fileLoadedEvent) {
                self.tempImage(fileLoadedEvent.target.result);
            };
            fileReader.readAsDataURL(fileToLoad);
        });

        self.save = function () {
            var form = {
                Name: self.name(),
                Tags: self.tags(),
                ReferenceId: self.referenceId(),
                ReferenceName: self.referenceName(),
                EntityTypeValue: 'AC',
                Description: self.description(),
                ImageData: self.tempImage()
            };
            
            ajax.post('folder', form).done(function (response) {
                if (response.id != '') {
                    window.location = '/folder/show?id=' + response.id;
                }
            });
        };

        $.subscribe('accountSelected', function (title, url, account) {
            if (!account.id()) {
                //NOTE: Tag can be used for multiple element binding
                return;
            }
            
            self.referenceId(account.id());
            self.referenceName(account.name());

            $.publish('hidePicker');
        });

        self.cancel = function () {
            window.location = "index";
        };
    };

    exports.exec = function (sectionId, model) {
        var viewModel = new ViewModel(model);
        ko.applyBindings(viewModel, document.getElementById(sectionId));
    };
    return exports;
});
